<template>
	<view class="baseForm">
		<!-- 选择加工单 -->
		<view>
			<u--input style="
					background-color: #fff;
					margin: 0 15px 5px 15px;
					height: 18px;
					border-radius: 5px;
				" v-model="processName" class="inputHeight" disabled @click="processSelect" placeholder="请选择工序"
				suffixIcon="arrow-down" clearable></u--input>
		</view>

		<!-- 搜索&扫码 -->
		<view class="upload-scan">
			<!-- <view class="searchButton" @click="dropdownOpen = true">
				{{ options1[value1 - 1].label }}
				<u-icon name="arrow-down"></u-icon>
			</view> -->
			<u-search v-model="searchText" shape="round" bgColor="#fff" :show-action="true" actionText="搜索"
				placeholder="请输入工单号查询" :animation="true" :clearabled="true" class="search" @search="searchList"
				@clear="clearList" @custom="searchList"></u-search>
			<!-- <u-icon v-if="value1 === 1" name="scan" size="27px" :bold="false" @click="openScan"></u-icon> -->

			<!-- 原生扫码 https 协议 -->
			<!-- <u-icon
				v-if="value1 === 1"
				name="scan"
				size="27px"
				:bold="false"
				@click="scanHandle"></u-icon> -->
		</view>
		<view class="upload-scan">
			<u--form labelPosition="left" :model="formData" labelWidth="55px">
				<u-form-item label="计划日期" labelWidth="80px" style="width: 100%">
					<view @click="openTimeSelect" class="flex input-box">
						<u--input v-model="planActualDate" border="none" disabled disabledColor="#ffffff"
							placeholder="请选择工单计划日期"></u--input>
					</view>
				</u-form-item>
			</u--form>
		</view>
		<!-- 当前作业 -->
		<view class="activeHeight" v-if="tableList.length > 0">
			<!-- 列表 -->
			<u-list ref="tableScroll" @scrolltolower="scrolltolower" class="list" :height="listHeight"
				lowerThreshold="50px" :pagingEnabled="true">
				<u-list-item v-for="(item, index) in tableList" :key="item.id" @click="selectItem(item)">
					<view class="card">
						<view class="flex record-title">
							<text class="line1">{{ item.materialName }}~{{ item.materialCode }}</text>
							<text>
								{{ item.processesClassificationName || "无" }}
							</text>
						</view>
						<view class="flex flex-col justify-between flex-1 h-full record-content-body">
							<view class="record-content">
								<view class="record-item">
									<text>计划开始时间</text>
									<text>
										{{ item.planBeginTime || "无" }}
									</text>
								</view>
								<view class="record-item">
									<text>计划结束时间</text>
									<text class="">
										<text>{{ item.planEndTime || "无" }}</text>
									</text>
								</view>
								<view class="record-item">
									<text>计划数量: {{ item.planQuantity || 0}}</text>
									<text>完成数量:{{ item.finishQuantity || 0}}</text>
								</view>
								<view class="record-item">
									<text>炉批次: {{ item.plannedBatch }}</text>
									<text>状态: {{ item.formStatusName }}</text>
								</view>
								<view class="record-item">
									<text>上工序完成数量: {{ item.upQuantity }}</text>
								</view>
								<u-line v-if="workOrderList[0]?.id == item.id" style="margin: 5px 0 2px"
									color="#dadbde"></u-line>
								<view style="
										display: flex;
										justify-content: space-between;
									">
									<view class="">工单号:{{ item.processingOrderNumber }}</view>
									<view v-if="workOrderList[0]?.id == item.id && processesClassification != 6" style="
											padding: 5px 15px 5px 15px;
											border-radius: 5px;
											color: #fff;
											font-size: 12px;
											height: 20px;
											line-height: 20px;
											background-color: #0379ff;
										">
										已选择
									</view>
								</view>
								<view style="
										display: flex;
										justify-content: space-between;
									" v-if="processesClassification == 6">
									<view v-if="workOrderList[0]?.id == item.id" style="
											padding: 5px 15px 5px 15px;
											border-radius: 5px;
											color: #ffffff;
											font-size: 12px;
											height: 20px;
											line-height: 20px;
											background-color: #67c23a;
										" @click="openTemperature()">
										温度填报
									</view>
									<view v-if="workOrderList[0]?.id == item.id" style="
											padding: 5px 15px 5px 15px;
											border-radius: 5px;
											color: #fff;
											font-size: 12px;
											height: 20px;
											line-height: 20px;
											background-color: #0379ff;
										">
										已选择
									</view>
								</view>
							</view>
						</view>
					</view>
				</u-list-item>
			</u-list>

			<view class="flex justify-center" v-show="tableLoading">
				<u-loading-icon color="#000a7b"></u-loading-icon>
			</view>
		</view>
		<!-- 空数据 -->
		<view v-show="tableList.length === 0 && !tableLoading">
			<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
		</view>
		<u-modal :show="showImportTemperature" ref="uModal1" confirmText="确认" :showCancelButton="true"
			@cancel="cancelImportTemperature" @confirm="confirmImportTemperature">
			<view class="slot-content">
				<u--form labelPosition="left" :model="formData" ref="uForm" :rules="rules" labelWidth="55px"
					errorType="toast">
					<u-form-item label="温度1:" prop="temperatureOne">
						<u--input style="height: 20px" v-model="formData.temperatureOne" class="inputHeight"
							placeholder="温度" clearable></u--input>
					</u-form-item>
					<u-form-item label="温度2:" prop="temperatureTwo">
						<u--input style="height: 20px" v-model="formData.temperatureTwo" class="inputHeight"
							placeholder="温度" clearable></u--input>
					</u-form-item>
					<u-form-item label="温度3:" prop="temperatureThree">
						<u--input style="height: 20px" v-model="formData.temperatureThree" class="inputHeight"
							placeholder="温度" clearable></u--input>
					</u-form-item>
				</u--form>
			</view>
		</u-modal>
		<!-- 工序选择器 -->
		<u-modal :show="showImport" ref="uModal" :content="`是否选择该加工单？`" confirmText="确认" showCancelButton
			@cancel="cancelImport" @confirm="confirmImport"></u-modal>
		<u-picker :show="show" :columns="columns" title="工序" keyName="processName" immediateChange cancel-text="取 消"
			@cancel="show = false" @confirm="confirmBtn"></u-picker>
		<u-datetime-picker v-model="planActualDateA" :show="showTime" mode="date" @cancel="showTime = false"
			@confirm="timeSelect"></u-datetime-picker>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, toRaw } from "vue";
	import { onShow, onPullDownRefresh, onLoad } from "@dcloudio/uni-app";
	import { http } from "@/utils/http";
	import { PageResult, TabInfo } from "@/types/type";
	import { useDictionaryStore } from "@/stores/useDictionaryStore";
	import { useUserStore } from '@/stores/useUserStore';
	import { useProduceStore } from "@/stores/useProduceStore";
	import { getSecondTime, getTimes } from "@/utils/common";

	// 实时获取
	const workOrderList = computed(
		() => JSON.parse(useProduceStore().workOrderList) || []
	);
	const crewMemberList = computed(() => JSON.parse(useProduceStore().crewMemberList));
	console.log("crewMemberList", crewMemberList.value[0])
	// 待完成数据
	const tableList = ref([]);
	const tableLoading = ref(false);
	const current = ref(0);
	const totalPage = ref(0);
	const total = ref(0);
	//列表高度
	const listHeight = ref("");

	onLoad(() => {
		// #ifdef H5
		listHeight.value = "calc(100vh - 88px)";
		// #endif

		// #ifdef APP-PLUS
		listHeight.value = "calc(100vh - 48px)";
		// #endif

		// 获取工序
		getProcessList()
	});

	onPullDownRefresh(() => {
		searchList();
		uni.stopPullDownRefresh();
	});
	const processesClassification = ref();
	async function loadmore(type ?: string) {
		try {
			current.value += 1;
			tableLoading.value = true;
			const result : PageResult<any> = await http({
				method: "POST",
				url: "/mes/mesplanworkingform/queryByPage",
				data: {
					current: current.value,
					size: 20,
					data: {
						processesClassification: processesClassification.value,
						processingOrderNumber: searchText.value,
						formStatusList: [2, 3],
						enabled: 1,
						deleted: 0,
						workingFormPlanActualDate: planActualDate.value,
						// planUser: crewMemberList.value[0].memberName,
					},
				},
			}).finally(() => {
				tableLoading.value = false;
			});
			const list = result.data;
			for (let i = 0; i < list.length; i++) {
				tableList.value.push(list[i]);
			}
			totalPage.value = result.page;
			total.value = result.total;
			type === "refresh" && uni.stopPullDownRefresh();
		} catch (e) {
			console.log(e);
		}
	}
	const scrolltolower = () => {
		totalPage.value > current.value && loadmore();
	};

	// 点击扫码
	const searchText = ref("");

	// 列表搜索
	function searchList() {
		current.value = 0;
		tableList.value = [];
		loadmore("refresh");
	}

	function clearList() {
		console.log("点击");
		searchText.value = "";
		searchList();
	}

	// 网页跳转
	// async function jump(item) {
	// 	uni.navigateTo({
	// 		url: `/pages/eam/equ/searchDeviceLedger/detail?assetId=${item.id}`,
	// 		fail: () => {
	// 			uni.showToast({
	// 				title: "敬请期待",
	// 				icon: "error",
	// 			});
	// 		},
	// 	});
	// }


	// --------------------------------------------------------------------- 选择工序
	// 获取工序列表
	const processList = ref([]);
	const getProcessList = async () => {
		await http({
			method: "POST",
			url: "/mes/mesprocess/getList",
			data: {
				plantId: crewMemberList.value[0].plantId,
				enabled: 1,
				deleted: 0,
			},
		}).then((res) => {
			columns.value[0] = res.data;
		});
	};
	const processName = ref("");
	const show = ref(false);
	const columns = ref([]);
	// 打开选择
	function processSelect() {
		show.value = true;
		uni.hideKeyboard();
	}
	// 确定选择
	function confirmBtn(e) {
		if (e.value.length) {
			processName.value = e.value[0].processName;
			searchText.value = "";
			tableList.value = [];
			getTabLiset(e.value[0].processType);
			// tableList.value = demo;
		}
		show.value = false;
	}
	// 根据选择的工序获取列表
	const getTabLiset = async (e) => {
		processesClassification.value = e
		loadmore();
	};

	// --------------------------------------------------------------------- 点击tableList item
	const hh = ref([]);
	const selectItem = (item) => {
		if (workOrderList.value[0]?.id == item.id) {
			return;
		}
		console.log(item);
		hh.value = item;
		showImport.value = true;
	};
	// 弹窗展示
	const showImport = ref(false);

	function cancelImport() {
		showImport.value = false;
	}
	function confirmImport() {
		showImport.value = false;
		useProduceStore().setWorkOrderList(toRaw(hh.value));
		console.log("workOrderList", workOrderList);
		uni.showToast({
			title: "选择成功",
		});
	}
	// --------------------------------------------------------------------- 工序
	const rules = ref({
		temperatureOne: [{
			type: "number",
			required: true,
			max: 10,
			message: "请输入数字",
			trigger: ["change"],
		},
		{
			// 自定义验证函数，见上说明
			validator: (rule, value, callback) => {
				// 上面有说，返回true表示校验通过，返回false表示不通过
				// uni.$u.test.mobile()就是返回true或者false的
				if (isNaN(parseFloat(value)) && isFinite(value)) {
					callback(new Error("请输入数字"));
				} else if (!/^\d{1,9}(\.\d{0,2})?$/.test(value)) {
					callback(new Error("请输入数字"));
				} else if (Number(value) < 0) {
					callback(new Error("请输入大于0的数"));
				} else {
					callback();
				}
			},
			trigger: ['change', 'blur'],
		}
		],
		temperatureTwo: [{
			type: "number",
			required: true,
			max: 10,
			message: "请输入数字",
			trigger: ["change"],
		},
		{
			// 自定义验证函数，见上说明
			validator: (rule, value, callback) => {
				// 上面有说，返回true表示校验通过，返回false表示不通过
				// uni.$u.test.mobile()就是返回true或者false的
				if (isNaN(parseFloat(value)) && isFinite(value)) {
					callback(new Error("请输入数字"));
				} else if (!/^\d{1,9}(\.\d{0,2})?$/.test(value)) {
					callback(new Error("请输入数字"));
				} else if (Number(value) < 0) {
					callback(new Error("请输入大于0的数"));
				} else {
					callback();
				}
			},
			trigger: ['change', 'blur'],
		}
		],
		temperatureThree: [{
			type: "number",
			required: true,
			max: 10,
			message: "请输入数字",
			trigger: ["change"],
		},
		{
			// 自定义验证函数，见上说明
			validator: (rule, value, callback) => {
				// 上面有说，返回true表示校验通过，返回false表示不通过
				// uni.$u.test.mobile()就是返回true或者false的
				if (isNaN(parseFloat(value)) && isFinite(value)) {
					callback(new Error("请输入数字"));
				} else if (!/^\d{1,9}(\.\d{0,2})?$/.test(value)) {
					callback(new Error("请输入数字"));
				} else if (Number(value) < 0) {
					callback(new Error("请输入大于0的数"));
				} else {
					callback();
				}
			},
			trigger: ['change', 'blur'],
		}
		],
	});
	const formData = ref({
		id: "",
		temperatureOne: "",
		temperatureTwo: "",
		temperatureThree: "",
	});
	const showImportTemperature = ref(false);
	function openTemperature() {
		getTemperatureInfo()
		showImportTemperature.value = true;
	}
	function rest() {
		formData.value.temperatureOne = "";
		formData.value.temperatureTwo = "";
		formData.value.temperatureThree = "";
	}

	function cancelImportTemperature() {
		rest();
		showImportTemperature.value = false;
	}
	const uForm = ref();
	const flag = ref(false)
	function confirmImportTemperature() {
		uForm.value.validate().then(async (valid : any) => {
			if (valid) {
				if (flag.value) {
					return;
				}
				flag.value = true;
				formData.value.id = workOrderList.value[0].id
				await http({
					method: "POST",
					url: "/mes/mesplanworkingform/updateTemperature",
					data: formData.value,
				}).then((res : any) => {
					if (res.code == 200) {
						uni.showToast({
							title: "温度填报成功！",
						});
						rest();
						showImportTemperature.value = false;
						flag.value = false;
					}
				}).finally(() => {
					rest();
					showImportTemperature.value = false;
					flag.value = false;
				});
			}
		});
	}

	async function getTemperatureInfo() {
		await http({
			method: "GET",
			url: `/mes/mesplanworkingform/get/` + workOrderList.value[0]?.id,
			data: formData.value,
		}).then((res : any) => {
			if (res.code == 200) {
				formData.value.id = workOrderList.value[0]?.id;
				formData.value.temperatureOne = res.data.temperatureOne;
				formData.value.temperatureTwo = res.data.temperatureTwo;
				formData.value.temperatureThree = res.data.temperatureTwo;
			}
		})
	}
	let planActualDate = ref(getTimes(new Date()).split(" ")[0]);
	let planActualDateA = ref(getTimes(new Date()).split(" ")[0]);
	const showTime = ref(false);
	function openTimeSelect() {
		if (!planActualDate.value) {
			planActualDate.value = getTimes(new Date()).split(" ")[0];
		}
		showTime.value = true;
		uni.hideKeyboard();
	}
	// 开始时间选择
	function timeSelect(e) {
		planActualDate.value = getTimes(e.value).split(" ")[0]
		planActualDateA.value = getTimes(e.value).split(" ")[0];
		showTime.value = false;
		current.value = 0;
		tableList.value = [];
		loadmore();
	}
</script>

<style lang="scss" scoped>
	uni-page-body {
		height: 100%;
		background-color: #fbfbff;
	}

	.search {
		:deep(.u-search__content) {
			box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
		}
	}

	.baseForm {
		background-color: #fbfbff;

		.tab-bar {
			padding: 0 20px;
		}

		.upload-scan {
			padding: $uni-page-padding;
			padding-top: 5px;
			padding-bottom: 5px;
			display: flex;
			align-items: center;

			// box-shadow: 0 1px 10px 0px rgb(19 10 236 / 10%);
			.u-icon {
				margin-left: 8px;
			}
		}

		.u-line {
			padding: 10px 0;
		}
	}

	.list {
		.card {
			margin: $uni-page-padding;
			margin-top: 5px;
			margin-bottom: 4px;
			border-radius: 7px;
			padding: 12px 12px 0px 12px;
			transition: all 300ms ease;
			border: 1px solid #efefef;
			background-color: #fff;

			.card-flex {
				display: flex;
				align-items: flex-start;
			}

			.right {
				flex: 1;
			}

			.title {
				font-size: 14px;
				line-height: 40px;
				height: 40px;
				margin-top: 8px;
				font-weight: bold;
				color: #101010;
				border-top: 1px solid #e5ebff;
			}

			.uni-btn {
				float: right;
				font-size: 12px;
				height: 24px;
				line-height: 24px;
				padding: 0 15px;
				margin-top: 7px;
				font-weight: 400;
			}

			.des {
				font-size: 12px;
				line-height: 20px;
				margin-bottom: 3px;
			}

			.left {
				flex-basis: calc(50% + 10px);
			}
		}
	}

	.record-title {
		display: flex;
		justify-content: space-between;
		margin: 2px 0 2px 0;
		color: $primary-color;

		uni-text:nth-child(1) {
			font-weight: bold;
			font-size: 15px;
		}

		uni-text:nth-child(2) {
			font-weight: bold;
			font-size: 15px;
			min-width: 60px;
			text-align: right;
		}
	}

	.record-item {
		margin: 7px 0 !important;
		color: #8f8e94 !important;
		word-break: break-all;
		font-size: 13px;
	}

	.record-item1 {
		color: #8f8e94 !important;
		word-break: break-all;
		font-size: 13px;
	}

	.record-content .record-item> :first-child {
		min-width: 70px !important;
	}

	:deep(.input-box) {
		// width: calc(100% - 56px);
		width: 100%;
		// border: 0.5px solid #dadbde !important;
		border-radius: 100px;
		height: 32px;
		line-height: 32px;
		box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
		background-color: #fff;

		.u-input {
			pointer-events: none;
			height: 32px;
			line-height: 32px;
			padding-left: 10px !important;
		}

		.uni-input-placeholder {
			color: rgb(144, 147, 153) !important;
			font-size: 14px;
		}

		.u-icon__icon {
			font-size: 22px !important;
			line-height: 22px;
			font-weight: normal;
			top: 0px;
			color: rgb(144, 147, 153) !important;
		}

		image {
			padding: 6px 6px;
			width: 20px;
			height: 20px;
		}
	}

	:deep(.search-btn) {
		width: 32px;
		height: 34px;
		margin-left: 4px;
		border-radius: 4px;
		background-color: transparent;
		border: none;

		// .u-icon__icon {
		// 	margin-left: 5px;
		// 	color: rgb(96, 98, 102) !important;
		// 	font-size: 26px !important;
		// }
		.u-button__text {
			color: rgb(96, 98, 102) !important;
		}
	}

	:deep(.searchButton) {
		color: rgb(41, 121, 255);
		font-size: 14px;
		width: 52px !important;
		min-width: 52px !important;
		display: flex;
		justify-content: flex-start;

		.u-icon {
			margin-left: 2px !important;
			font-size: 14px;

			.u-icon__icon {
				font-size: 14px !important;
				line-height: 14px !important;
			}
		}
	}

	:deep(.u-dropdown) {
		flex: none !important;
		width: 52px;

		.u-cell-group__wrapper {
			// border: 1px solid rgb(214, 215, 217);
			// border-radius: 4px;
			border-right: 1px solid rgb(214, 215, 217);
			border-left: 1px solid rgb(214, 215, 217);
		}

		// .u-line { display: none;}
		.u-cell__body {
			padding: 8px 10px !important;
			// border: 1px solid #8f8e94;
		}

		.u-dropdown__content__mask {
			background-color: transparent;
		}
	}

	// :deep(.u-drawdown-item__content) {
	// 	top: 88px !important;
	// 	.common-search {
	// 		display: flex;
	// 		justify-content: flex-start;
	// 		margin: 0 15px;
	// 		padding: 13px 5px;
	// 		border-bottom: 1px solid rgb(214, 215, 217);
	// 	}
	// }

	// :deep(.dis-none){
	// 		.u-dropdown__content{
	// 			display: none;
	// 		}
	// 	}
</style>